package com.gitee.tianchaohongyu.jdcl.aspect;

import com.gitee.tianchaohongyu.jdcl.configuration.JdclProperties;
import com.gitee.tianchaohongyu.jdcl.core.CleanService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 抽象切面
 */
public abstract class AbstractParamsAspect implements Ordered {

  @Autowired
  private JdclProperties jdclProperties;
  @Resource
  private CleanService cleanService;

  @Override
  public int getOrder() {
    return jdclProperties.getAspectOrder();
  }

  /**
   * 清洗切入点
   *
   * @param proceedingJoinPoint 进行中的切入点
   * @return 返回界面清洗后的切点返回值
   */
  protected Object cleanJoinPoint(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    Signature signature = proceedingJoinPoint.getSignature();
    Object[] args = proceedingJoinPoint.getArgs();
    String name = String.format("%s.%s", signature.getDeclaringType().getSimpleName(), signature.getName());
    if (signature instanceof MethodSignature) {
      //如果是方法上执行
      Method method = ((MethodSignature) signature).getMethod();
      cleanService.cleanMethod(name, method, args);
    } else {
      for (int i = 0; i < args.length; i++) {
        Object arg = args[i];
        if (arg != null) cleanService.cleanFields(String.format("%s(%s)", name, i), arg);
      }
    }
    return proceedingJoinPoint.proceed(args);
  }
}
